#include <QObject>
#include <QWidget>
#include <QDialog>
#include <QCloseEvent>
#include <QPushButton>
#include <QThread>

#include <QApplication>
#include <QHBoxLayout>

#include "Thread.h"
#include "ThreadDialog.h"

#include <cstdlib>

Thread::Thread(){
	stopped=false;
}

void Thread::setMessage(const QString &msg){
	
}

void Thread::stop(){
	stopped=true;
}

void Thread::run(){
	while(!stopped){
		sleep(1);
	}
	stopped=false;
}


ThreadDialog::ThreadDialog(QWidget* parent) : QDialog(parent){
	QHBoxLayout* layout=new QHBoxLayout(this);
	layout->setSpacing(6);
	layout->setMargin(9);
	btna=new QPushButton("start a",this);
	layout->addWidget(btna);
	btnb=new QPushButton("start b",this);
	layout->addWidget(btnb);
	btnquit=new QPushButton("quit",this);
	layout->addWidget(btnquit);
	
	btnquit->setDefault(true);
	
	connect(btna,SIGNAL(clicked()),this,SLOT(startOrStopThreadA()));
	connect(btnb,SIGNAL(clicked()),this,SLOT(startOrStopThreadB()));	
	connect(btnquit,SIGNAL(clicked()),this,SLOT(close()));

	setLayout(layout);
}


void ThreadDialog::closeEvent(QCloseEvent* event){
	threadA.stop();
	threadB.stop();
	threadA.wait();
	threadB.wait();
	event->accept();
}

void ThreadDialog::startOrStopThreadA(){
	if(threadA.isRunning()){		
		threadA.stop();
		//threadA.wait();
		btna->setText(tr("start a"));
	}else{
		threadA.start();
		btna->setText(tr("stop a"));
	}
}

void ThreadDialog::startOrStopThreadB(){
	if(threadB.isRunning()){		
		threadB.stop();
		//threadA.wait();
		btnb->setText(tr("start a"));
	}else{
		threadB.start();
		btnb->setText(tr("stop a"));
	}
}

int main(int argc,char* argv[]){
	QApplication app(argc,argv);
	
	ThreadDialog dlg;
	dlg.show();
	
	return app.exec();
}


